#!/usr/bin/env python3
import sys
from scapy.all import Ether, TCP, UDP, IPOption, Packet, bind_layers, get_if_list, sniff
from scapy.fields import BitField, XShortField
from scapy.layers.inet import _IPOption_HDR

def get_net_interface():
    """获取网络接口"""
    ifaces = [i for i in get_if_list() if "eth0" in i]
    return ifaces[0] if ifaces else None

class IPOption_MRI(IPOption):
    """MRI IP选项头部"""
    name = "MRI"
    option = 31
    fields_desc = [ 
        _IPOption_HDR,
        FieldLenField("length", None, fmt="B", length_of="swids", adjust=lambda pkt,l:l+4),
        ShortField("count", 0),
        FieldListField("swids", [], IntField("", 0), length_from=lambda pkt:pkt.count*4)
    ]

class SourceRouteHeader(Packet):
    """源路由头部"""
    fields_desc = [ 
        BitField("bos", 0, 1),    # 栈起始标志
        BitField("port", 0, 15)   # 端口号
    ]

class SourceRouteTail(Packet):
    """源路由尾部"""
    fields_desc = [ 
        XShortField("etherType", 0x800)  # 以太网类型
    ]

def process_packet(pkt):
    """处理接收到的数据包"""
    print("收到数据包")
    pkt.show2()
    sys.stdout.flush()

def setup_protocol_bindings():
    """设置协议层绑定"""
    bind_layers(Ether, SourceRouteHeader, type=0x1234)
    bind_layers(SourceRouteHeader, SourceRouteHeader, bos=0)
    bind_layers(SourceRouteHeader, SourceRouteTail, bos=1)

def main():
    """主函数"""
    iface = get_net_interface()
    if not iface:
        print("找不到eth0接口")
        return 1
    
    setup_protocol_bindings()
    print(f"在接口 {iface} 上监听")
    sys.stdout.flush()
    
    sniff(iface=iface, prn=process_packet)
    return 0

if __name__ == '__main__':
    sys.exit(main())